﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Tasks;

using Visifire.Charts;
using sil;
using ESRI.ArcGIS.Client.Symbols;
using System.Threading;
using System.Windows.Threading;

using System.Collections.ObjectModel;

using GisWeb.ServiceReference1;



namespace GisWeb
{
    public partial class MainPage : UserControl
    {
        Draw predictDraw;

        //点击对比分析按钮
        private void btnAbout1_Click(object sender, RoutedEventArgs e)
        {
            switch (mapclick)
            {
                case 0: //myMap.MouseClick += new EventHandler<Map.MouseEventArgs>(myMap_MouseClick);

                    // baseWindow.ParentLayoutRoot = paraFolder;
                    //comBaseWindow.Show();
                    //comBaseWindow.Closed += new EventHandler(comBaseWindow_Closed);
                    //comBaseWindow.singleChoose += (object pa, EventArgs ea) => { MyDraw.DrawMode = DrawMode.Point; MyDraw.IsEnabled = true; };
                    //comBaseWindow.multiChoose += (object pa, EventArgs ea) => { MyDraw.DrawMode = DrawMode.Rectangle; MyDraw.IsEnabled = true; };

                    // baseWindow.closeButton += new EventHandler(baseWindow_closeButton);
                    // baseWindow.Closed += baseWindow_closeButton;
                    preBaseWindow.Show();
                    preBaseWindow.showFlag = 1;
                    predictDraw = new Draw(myMap);
                    preBaseWindow.singleChoose += (object pa, EventArgs ea) => { predictDraw.DrawMode = DrawMode.Point; predictDraw.IsEnabled = true; };
                    preBaseWindow.multiChoose += (object pa, EventArgs ea) => { predictDraw.DrawMode = DrawMode.Rectangle; predictDraw.IsEnabled = true; };
                    preBaseWindow.stopCom += preBaseWindow_Closed;
                    preBaseWindow.stopDraw += (object pa, EventArgs ea) => { predictDraw.IsEnabled = false; };
                    preBaseWindow.clearSelection += (object pa, EventArgs ea) => { gra.Graphics.Clear(); cityGroup.Clear(); preChart.Series.Clear(); };
                    predictDraw.DrawComplete += new EventHandler<DrawEventArgs>(predictDraw_DrawComplete);
                    preBaseWindow.alterType += new EventHandler(preBaseWindow_alterType);
                    mapclick = 3;
                    break;
                case 1: MessageBox.Show("正在运行基础查询模块，请先停止再进行查询"); break;
                case 2: MessageBox.Show("正在运行对比分析模块，请先停止再进行查询"); break;
                case 3: MessageBox.Show("正在运行经济指数预测模块，请先停止再进行查询"); break;
                case 4: MessageBox.Show("正在运行投资分析模块，请先停止再进行查询"); break;
                case 5: MessageBox.Show("正在运行重心转移模块，请先停止再进行查询"); break;

            }
        }

        void preBaseWindow_alterType(object sender, EventArgs e)
        {
            List<String> citys = new List<string>();
            foreach(Graphic graph in cityGroup){
            
            citys.Add(graph.Attributes["NAME"].ToString());
            }
            preChart.Series.Clear();
            ServiceReference1.GISServiceClient client = new GISServiceClient();
            //MessageBox.Show(preBaseWindow.predictType.SelectedItem.ToString());
            client.GetTimeSeriesListCompleted += new EventHandler<GetTimeSeriesListCompletedEventArgs>(client_GetTimeSeriesListCompleted);
            client.GetTimeSeriesListAsync(citys, (preBaseWindow.predictType.SelectedItem as TextBlock).Text);
            
        }


        //画图完后执行的操作
        void predictDraw_DrawComplete(object sender, DrawEventArgs e)
        {
            QueryTask queryTask = new QueryTask("http://arcgis:6080/arcgis/rest/services/HuNanMapService/MapServer/3");


            //查询后执行的操作
            queryTask.ExecuteCompleted += QueryTask;

            //查询失败后执行的操作
            //queryTask.Failed += QueryTask_Failed;
            GraphicsLayer graphicsLayer = myMap.Layers["gra"] as GraphicsLayer;


            Query query = new ESRI.ArcGIS.Client.Tasks.Query();
            // Specify fields to return from query
            query.OutFields.Add("*");
            query.Geometry = e.Geometry;
            query.Where = "1=1";
            // Return geometry with result features
            query.ReturnGeometry = true;
            query.OutSpatialReference = myMap.SpatialReference;

            queryTask.ExecuteAsync(query);
        }

        void QueryTask(object sender, QueryEventArgs args)
        {
            //查询后的结果存储在这里
            FeatureSet featureSet = args.FeatureSet;

            if (featureSet == null || featureSet.Features.Count < 1)
            {
                MessageBox.Show("No features returned from query");
                return;
            }
            GraphicsLayer graphicsLayer = myMap.Layers["gra"] as GraphicsLayer;

            //查询的结果非空时
            if (featureSet != null && featureSet.Features.Count > 0)
            {
                List<String> predictCity = new List<string>();
                foreach (Graphic feature in featureSet.Features)
                {
                    feature.Symbol = LayoutRoot.Resources["fill"] as SimpleFillSymbol;
                    // 

                    // if (cityGroup.Contains(feature)) { continue; }
                    // MessageBox.Show(cityGroup.Contains(feature).ToString());
                    //查询的区域的信息存储在cityGroup中

                    cityGroup.Add(feature);
                    int multi_select = 0;
                    for (int i = 0; i < cityGroup.Count - 1; i++)
                    {
                        if (cityGroup[i].Attributes["NAME"].ToString() == feature.Attributes["NAME"].ToString())
                        {
                            multi_select = 1;
                            cityGroup.RemoveAt(cityGroup.Count - 1);
                            break;
                        }
                    }
                    if (multi_select == 0)
                    {
                        graphicsLayer.Graphics.Insert(0, feature);
                        predictCity.Add(feature.Attributes["NAME"].ToString());
                    }



                }

                ServiceReference1.GISServiceClient client = new GISServiceClient();
                //MessageBox.Show(preBaseWindow.predictType.SelectedItem.ToString());
                client.GetTimeSeriesListCompleted+=new EventHandler<GetTimeSeriesListCompletedEventArgs>(client_GetTimeSeriesListCompleted);
                client.GetTimeSeriesListAsync(predictCity, (preBaseWindow.predictType.SelectedItem as TextBlock).Text, preBaseWindow.predictType.SelectedIndex);
             
               
            }
        }

        void client_GetTimeSeriesListCompleted(object sender, GetTimeSeriesListCompletedEventArgs e) {

            List<MyTimeSeries> resultSet = e.Result;
       
            foreach (MyTimeSeries result in resultSet) {
              //  MessageBox.Show(result.Times.Last() + result.Titel + result.Values.Last());
                DataSeries series = new DataSeries();
                series.LegendText = result.Titel;
             
                for (int i = 0; i < result.Times.Count; i++) {
                    DataPoint dp = new DataPoint();
                    dp.XValue = int.Parse(result.Times[i].ToString().Substring(0,4));
                    dp.AxisXLabel = dp.XValue + "";
                    dp.YValue = Math.Floor((double.Parse(result.Values[i].ToString())) / 1000000);
                   

                    //改变颜色
                    if (int.Parse(result.Times[i].ToString().Substring(0, 4)) > 2011)
                    {
                        dp.Color = new SolidColorBrush(Color.FromArgb(255, 243, 233, 233));

                    }
                    else { dp.Color = new SolidColorBrush(Color.FromArgb(255, 209, 164, 62)); }
                    series.DataPoints.Add(dp);
                
                }
                
                series.Name = result.Titel;
                series.ToolTipText = "#AxisXLabel,#Series,#YValue";
                int select = preResultWindow.combo.SelectedIndex;
                switch (select) {

                    case 0: series.RenderAs = RenderAs.Column; break;
                    case 1: series.RenderAs = RenderAs.Bar; break;
                    case 2: series.RenderAs = RenderAs.StackedBar; break;
                    case 3: series.RenderAs = RenderAs.StackedArea; break;
                
                
                
                
                }
         
                preChart.Series.Add(series);
                preChart.Titles.Clear();
                Title tit = new Title();
                tit.Text = (preBaseWindow.predictType.SelectedItem as TextBlock).Text + "未来三年预测数据";
                preChart.Titles.Add(tit);
                try
                {
                    preResultWindow.LayoutRoot.Children.Add(preChart);
                }
                catch (Exception ttt) { Console.Write(ttt.Message); }
                try { preResultWindow.Show(); preResultWindow.showFlag = 1; }
                catch(Exception ttt){ Console.Write(ttt.Message);}
            }
        
        
        
        }

        void preBaseWindow_Closed(object sender, EventArgs e)
        {
            gra.Graphics.Clear();
            //关闭结果窗口
            preBaseWindow.single.IsChecked = false;
            preBaseWindow.multi.IsChecked = false;
            preChart.Series.Clear();
            cityGroup.Clear();
            predictDraw.IsEnabled = false;
            preResultWindow.Close();
            preBaseWindow.Close();
            mapclick = 0;
        }

       


    }
}